package io.github.jast90.internship.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * Created by jast90 on 2021/1/1
 */
@Service
public class OssService {

    @Value("${oss.endpoint:oss-cn-beijing.aliyuncs.com}")
    private String endpoint ;
    @Value("${oss.accessKeyId:LTAI4G781EQEp9bAN3rYVDDf}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret:hgR12KgY5m1K7sxufWZ1Kq6ZdeI1dY}")
    private String accessKeySecret;
    @Value("${oss.baseUrl:oss-cn-beijing.aliyuncs.com}")
    private String url;

    public String uploadFile(InputStream inputStream,String bucketName,
                              String objectName){
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucketName,objectName,inputStream);
            return String.format("https://%s.%s/%s",bucketName,url,objectName);
        }finally {
            ossClient.shutdown();
        }
    }

}
